from django.db import transaction
from django.http import JsonResponse
from rest_framework.views import APIView
from .models import Role
from role.serializers import RoleListSerializer, TreeSerializer
from .validate import AddValidate, EditValidate, GrantValidate
from utils.utils import responseSuccess, responseError, validateError, serializerJSON, filterFields

# 系统管理-角色管理-表格数据
class ListAPI(APIView):
    def get(self,req):
        queryDict = req.query_params.dict()
        filterDict = filterFields(Role, queryDict)
        filterDict['parentId'] = filterDict.pop('parentId', None)
        roles = Role.objects.filter(**filterDict)
        serializers = RoleListSerializer(roles, many=True, context={'exclude': ['hasChildren']})
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(datas), safe=False)

# 角色完整树结构序列化
class TreeAPI(APIView):
    def get(self,req):
        serializers = TreeSerializer(Role.objects.filter(parentId=None), many=True, context={'fields': ['id', 'roleName', 'children']})
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(datas), safe=False)

# 新增/修改
class SubmitAPI(APIView):
    # 新增
    def post(self,req):
        data = req.data
        edit_id = data.get('id')
        if edit_id:
            role = Role.objects.get(id=int(edit_id))
            form = EditValidate(role, data=data)
        else:
            form = AddValidate(data=data)
        if form.is_valid():
            if edit_id:
                obj = form.update(role, form.validated_data)
            else:
                obj = form.create(form.validated_data)
            return JsonResponse(responseSuccess(str(obj.pk)), safe=False)
        # 格式化错误信息
        arr = validateError(form.errors)
        return JsonResponse(responseError(arr), safe=False)

# 删除
class RemoveAPI(APIView):
    def post(self,req):
        ids = req.query_params.dict().get('ids')
        if not ids:
            return JsonResponse(responseError('ids不能为空'), safe=False)
        ids = ids.split(',')
        if not Role.objects.filter(id__in=ids).exists():
            return JsonResponse(responseError('删除对象不存在'), safe=False)
        for i in Role.objects.filter(id__in=ids):
            if i.role_set.exists():
                return JsonResponse(responseError('请先删除子节点'), safe=False)
        result = Role.objects.filter(id__in=ids).delete()
        if result:
            return JsonResponse(responseSuccess(), safe=False)
        return JsonResponse(responseError('删除失败'), safe=False)

# 给角色分配菜单
class GrantAPI(APIView):
    def post(self,req):
        data = req.data
        validate = GrantValidate(data=data)
        if not validate.is_valid():
            err = validateError(validate.errors)
            return JsonResponse(responseError(err), safe=False)
        with transaction.atomic():
            validate.create(validate.validated_data)
        return JsonResponse(responseSuccess(), safe=False)
        